<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5                                                          |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | This source file is subject to version 3.00 of the PHP License,        |
// | that is available at http://www.php.net/license/3_0.txt.               |
// | If you did not receive a copy of the PHP license and are unable to     |
// | obtain it through the world-wide-web, please send a note to            |
// | license@php.net so we can mail you a copy immediately.                 |
// +------------------------------------------------------------------------+
// | Author:                                                                |
// +------------------------------------------------------------------------+
//
// $Id$
//


/**
* @author       vv
*/
abstract class SmartPHP_Db_Table
{
    /**
    * @var      string
    */
    protected $_primaryKey ;

    /**
    * @var      object
    */
    protected $_db;
    /**
     * _defaultDb 
     * 
     * @var mixed
     * @access protected
     */
    protected static $_defaultDb;

	/**
	 * _tblName 
	 * 
	 * @var mixed
	 * @access protected
	 */
	protected $_tblName;
    
    /**
    * @return   void
    */
    public function __construct()
    {
		$this->_setDbAdapter();
    }
    
    /**
    * @param    mixed $para    
    * @return   array
    */
    public function find($para)
    {
		$select = $this->select();
		$sql = $select->from($this->_tblName)->where($this->_primaryKey . "=:id")->__toString();
		$stmt = $this->_db->prepare($sql);
		$stmt->bindParam(":id" , $para , PDO::PARAM_INT);
		$stmt->execute();
		return $stmt->fetch();
    }
    
    /**
    * @param    array $data    
    * @return   int
    */
    public function insert($data)
    {
		if( !is_array($data) )
		{
			throw new SmartPHP_Db_Select_Exception("Parameter must be an array!"); 
		}
		$fieldsStr = implode( "," , array_keys($data) );
		$data = array_map("mysql_escape_string" , $data);
		$valuesStr = "'" . implode("' , '" , $data) . "'";
		$sql = "INSERT INTO " . $this->_tblName . " (" . $fieldsStr . ") VALUES (" . $valuesStr . ")";
		if($this->_db->exec($sql))
		{
			 return $this->_db->lastInsertId();
		}
		else 
		{
			 throw new SmartPHP_Db_Table_Exception("Insert data failed");
		}
    }
    
    /**
    * @param    array $data    
    * @param    string $cond    
    * @return   int
    */
    public function replace($data, $cond)
    {
		if( !is_array($data) )
		{
			throw new SmartPHP_Db_Select_Exception("Parameter must be an array!"); 
		}
		$fieldsStr = implode( "," , array_keys($data) );
		$data = array_map("mysql_escape_string" , $data);
		$valuesStr = "'" . implode("' , '" , $data) . "'";
		$sql = "REPLACE INTO " . $this->_tblName . " (" . $fieldsStr . ") VALUES (" . $valuesStr . ")";
		if($this->_db->exec($sql))
		{
			 return $this->_db->lastInsertId();
		}
		else 
		{
			 throw new SmartPHP_Db_Table_Exception("Insert data failed");
		}
    }
    
    /**
    * @param    array $data    
    * @param    string $cond    
    * @return   int
    */
    public function update($data, $cond)
    {
		$sql = "UPDATE " . $this->_tblName . " SET ";
		$tag = 0;
		foreach($data as $key=>$val)
		{
			$sql .= $tag == 0 ? "" : " , "; 
			$sql .= "`$key` = '" . mysql_escape_string($val) . "'";
		}
		$sql .= " WHERE " . $cond;
		return $this->_db->exec($sql);
    }
    
    /**
    * @param    string $cond    
    * @return   int
    */
    public function delete($cond)
    {
		$sql = "DELETE FROM " . $this->_tblName . " WHERE " . $cond;
		return $this->_db->exec($sql);
    }

	/**
	 * remove 
	 * 
	 * @param mixed $id 
	 * @access public
	 * @return void
	 */
	public function remove($id)
	{
		 return $this->delete($this->_primaryKey . "= $id");
	}
    
    /**
    * @param    string $field    
    * @param    string $cond    
    * @return   mixed
    */
    public function getOne($field , $cond = null , $order = null)
    {
		$row = $this->getRow($field , $cond , $order);
		return $row[0];
    }
    
    /**
    * @param    string $cond    
    * @param    mixed $field    
    * @return   array
    */
    public function getRow( $field = "*" ,$cond = null , $order = null)
    {
		$arr = $this->getAll($field , $cond , $order , 0 , 1);
		return $arr[0];
    }
    
    /**
    * @param    string $cond    
    * @param    mixed $field    
    * @return   array
    */
    public function getAll($field = "*" , $cond = null, $order = null , $offset = null , $num = null )
    {
		$select = $this->select()->fields($field)->from($this->_tblName);
		if($cond) 	$select->where($cond);
		if($order)  $select->order($order);
		if($num) 	$select->limit($offset , $num);
		$sql = $select->__toString();
		return $this->_db->query($sql);
    }
    
    
    
    /**
     * getDbAdapter 
     * 
     * @access public
     * @return void
     */
    public function getDbAdapter()
    {
		return $this->_db;
    }
    
    /**
    * @return   object
    */
    public function setPrimaryKey( $primaryKey )
    {
		$this->_primaryKey = $primaryKey;
    }
    
    /**
    * @return   object
    */
    public function select()
    {
		require_once("SmartPHP/Db/Select.php");
		return new SmartPHP_Db_Select();
    }
    
    /**
     * _setDbAdapter 
     * 
     * @param mixed $db 
     * @access protected
     * @return void
     */
    protected function _setDbAdapter($db = null)
    {
		if($db === null)
		{
			 $this->_db = self::getDefaultAdapter();
		}
		else
		{
			 $this->_db = self::_setupDbAdapter($db);
		}
		return $this;
    }

	/**
	 * _setupDbAdapter 
	 * 
	 * @param mixed $db 
	 * @static
	 * @final
	 * @access public
	 * @return void
	 */
	public static final function _setupDbAdapter($db)
	{
		if($db === null)
		{
			 return null;
		}
		if(is_object($db) && (!$db instanceOf PDO))
		{
			 throw new SmartPHP_Db_Table_Exception("param must be a string or an instanceOf PDO");
		}
		if(is_string($db))
		{
			require_once("SmartPHP/Pool.php");	 
			$db = SmartPHP_Pool::get($db);
		}
		return $db;
	}

	/**
	 * setDefaultAdapter 
	 * 
	 * @param mixed $db 
	 * @static
	 * @final
	 * @access public
	 * @return void
	 */
	public static final function setDefaultAdapter($db)
	{
		self::$_defaultDb = self::_setupDbAdapter($db);
	}
	/**
	 * getDefaultAdapter 
	 * 
	 * @static
	 * @final
	 * @access public
	 * @return object
	 */
	public static final function getDefaultAdapter()
	{
		return self::$_defaultDb; 
	}
}

?>
